<template>
  <div>
    <el-date-picker v-model="year" type="year" value-format="YYYY" placeholder="选择查询年份"
      @change="searchYear"></el-date-picker>
    <!-- 下拉选择框 -->
    <el-select v-model="selectedChart" placeholder="选择统计图" @change="onChartSelect"
      style="margin-left: 20px; width: 300px">
      <el-option label="平均薪资饼状图" value="avgSalaryPieChart" />
      <el-option label="就业率饼状图" value="employmentRatePieChart" />
      <el-option label="薪资分布柱状图" value="majorSalaryBarChart" />
      <el-option label="入职时间薪资分布柱状图" value="avgSalaryChart" />
    </el-select>

    <!-- 平均薪资饼状图 -->
    <div v-if="selectedChart === 'avgSalaryPieChart'">
      <div v-if="hasData1" style="display: inline-block; margin-top: 30px;margin-left: 50px;">
        <div ref="avgSalaryPieChartRef" style="width: 600px; height: 500px; margin-bottom: 30px;"></div>
      </div>
      <div v-else style="display: inline-block; margin-top: 30px;">
        <div
          style="width: 600px; height: 500px; margin-bottom: 30px; display: flex; align-items: center; justify-content: center;margin-left: 50px;">
          <span style="color: #999;">暂无数据</span>
        </div>
      </div>
    </div>

    <!-- 就业率饼状图 -->
    <div v-if="selectedChart === 'employmentRatePieChart'">
      <div v-if="hasData2" style="display: inline-block;">
        <div ref="employmentRatePieChartRef" style="width: 600px; height: 500px; margin-top: 30px;margin-left: 50px;"></div>
      </div>
      <div v-else style="display: inline-block;">
        <div
          style="width: 600px; height: 500px; margin-bottom: 30px; display: flex; align-items: center; justify-content: center;margin-left: 50px;">
          <span style="color: #999;">暂无数据</span>
        </div>
      </div>
    </div>

    <!-- 薪资分布柱状图 -->
    <div v-if="selectedChart === 'majorSalaryBarChart'">
      <h2>薪资分布折线图</h2>
      <div v-if="hasData3">
        <div ref="majorSalaryBarChartRef" style="width: 700px; height: 400px;"></div>
      </div>
      <div v-else>
        <div style="width: 700px; height: 400px; display: flex; align-items: center; justify-content: center;">
          <span style="color: #999;">暂无数据</span>
        </div>
      </div>
    </div>

    <!-- 入职时间薪资分布柱状图 -->
    <div v-if="selectedChart === 'avgSalaryChart'">
      <h2>入职时间薪资分布柱状图</h2>
      <div v-if="hasData4">
        <div ref="avgSalaryChartRef" style="width: 700px; height: 400px;"></div>
      </div>
      <div v-else>
        <div style="width: 700px; height: 400px; display: flex; align-items: center; justify-content: center;">
          <span style="color: #999;">暂无数据</span>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { getMajorStatisticsApi } from '@/api/api';
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';

// 查询条件
const year = ref(new Date().getFullYear().toString());
const hasData1 = ref(false);
const hasData2 = ref(false);
const hasData3 = ref(false);
const hasData4 = ref(false);


// 选择的统计图
const selectedChart = ref("avgSalaryPieChart"); // 默认选择第一个统计图

// 平均薪资饼状图
const avgSalaryPieChartRef = ref(null);
// 就业率饼状图
const employmentRatePieChartRef = ref(null);
// 薪资分布柱状图
const majorSalaryBarChartRef = ref(null);
//入职时间新增变化
const avgSalaryChartRef = ref(null);


// 创建平均薪资饼状图
const createAvgSalaryPieChart = async (data: any[]) => {
  await nextTick(); // 确保 DOM 已经更新
  if (avgSalaryPieChartRef.value) {
    const chart = echarts.init(avgSalaryPieChartRef.value);
    const option = {
      title: {
        text: '平均薪资饼状图',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
      },
      series: [
        {
          name: '平均薪资',
          type: 'pie',
          radius: '50%',
          data: data.map((item: any) => ({
            value: Math.round(item.avgSalary),
            name: `${item.majorName} ${Math.round(item.avgSalary)}`,
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    };
    chart.setOption(option);
  }
};

// 创建就业率饼状图
const createEmploymentRatePieChart = async (data: any[]) => {
  await nextTick(); // 确保 DOM 已经更新
  if (employmentRatePieChartRef.value) {
    const chart = echarts.init(employmentRatePieChartRef.value);
    const option = {
      title: {
        text: '就业率饼状图',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
      },
      series: [
        {
          name: '就业率',
          type: 'pie',
          radius: '50%',
          data: data.map((item: any) => ({
            value: Math.round(item.employmentRate * 100),
            name: `${item.majorName} ${Math.round(item.employmentRate * 100)}%`,
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    };
    chart.setOption(option);
  }
};

// 创建薪资分布柱状图
const createMajorSalaryBarChart = async (data: any) => {
  await nextTick(); // 确保 DOM 已经更新
  if (majorSalaryBarChartRef.value) {
    // 销毁之前的图表实例，如果存在
    echarts.dispose(majorSalaryBarChartRef.value);
    const chart = echarts.init(majorSalaryBarChartRef.value);

    const salaryRangeLabels = [
      '4000以下',
      '4000-6000',
      '6000-8000',
      '8000-10000',
      '10000以上',
    ];

    const salaryRanges = [
      { range: [0, 4000], count: {} },
      { range: [4000, 6000], count: {} },
      { range: [6000, 8000], count: {} },
      { range: [8000, 10000], count: {} },
      { range: [10000, Infinity], count: {} },
    ];

    // 直接从 response.data 提取 majorSalaryList
    const { majorSalaryList } = data;

    majorSalaryList.forEach((salary: any) => {
      salaryRanges.forEach((range: any) => {
        if (
          salary.empSalary >= range.range[0] &&
          salary.empSalary < range.range[1]
        ) {
          const majorName = salary.majorName;
          range.count[majorName] = (range.count[majorName] || 0) + 1;
        }
      });
    });

    // 获取唯一的专业名称集合
    const uniqueMajors = [...new Set(majorSalaryList.map((s: any) => s.majorName))];

    // 柱状图
    const barSeries = uniqueMajors.map((majorName: any, index: number) => ({
      name: majorName,
      type: 'bar',
      data: salaryRanges.map((range: any) => range.count[majorName] || 0),
      label: {
        show: true, // 在柱顶显示数据
        position: 'top',
        formatter: (params: any) => {
          return params.value === 0 ? '' : params.value; // 值为0时不显示
        },
      },
    }));


    // 折线图
    const lineSeries = uniqueMajors.map((majorName: any, index: number) => ({
      name: majorName,
      type: 'line',
      data: salaryRanges.map((range: any) => range.count[majorName] || 0),
      yAxisIndex: 0, // 使用与柱状图相同的y轴
      itemStyle: {
      },
      label: {
        show: true, // 在线上显示数据
        position: 'top',
        formatter: (params: any) => {
          return params.value === 0 ? '' : params.value; // 值为0时不显示
        },
      },
      markLine: {
        symbol: 'circle',
        symbolSize: 6,
        data: [
          {
            type: 'max',
            name: '最大值',
          },
        ],
      },
    }));

    // 设置全局配置，确保柱状图和折线图的颜色一致
    const option = {
      title: {
        text: '薪资分布折线图',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: {
        data: uniqueMajors,
        bottom: 0,
      },
      xAxis: {
        type: 'category',
        data: salaryRangeLabels,
        axisLabel: {
          // 用于确保折点位置对齐柱状图中心
          interval: uniqueMajors.length - 1, // 对齐柱状图中心
        },
      },
      yAxis: {
        type: 'value',
        name: '人数',
      },
      // series: [...barSeries,...lineSeries], // 合并柱状图和折线图系列
      series: [...lineSeries], // 合并柱状图和折线图系列
    };

    chart.setOption(option);
  }
};

// 创建入职时间新增变化图表
const createAvgSalaryBarChart = async (data: any) => {
  await nextTick(); // 确保 DOM 已经更新

  if (avgSalaryChartRef.value) {
    // 销毁之前的图表实例，如果存在
    echarts.dispose(avgSalaryChartRef.value);

    const chart = echarts.init(avgSalaryChartRef.value);

    // 从数据中提取 avgSalaryList
    const { avgSalaryList } = data;

    // 获取唯一的 yearOfEmployment 值作为横坐标数据
    const years = [...new Set(avgSalaryList.map((item: any) => item.yearOfEmployment))].sort(
      (a: any, b: any) => a - b
    );

    // 获取唯一的 majorName 值，用于区分不同的专业
    const majors = [...new Set(avgSalaryList.map((item: any) => item.majorName))];

    // 根据专业创建数据 series
    const series = majors.map((major) => {
      return {
        name: major,
        type: 'bar',
        data: years.map((year) => {
          // 查找当前 year 和 major 的记录数
          const record = avgSalaryList.find(
            (item: any) =>
              item.yearOfEmployment === year && item.majorName === major
          );
          return record ? (record.avgSalary).toFixed(0) : 0; // 如果没有匹配数据则返回 0
        }),
        label: {
          show: true, // 在柱的顶部显示数据
          position: 'top',
          formatter: (params: any) => {
            return params.value === 0 ? '' : params.value; // 值为0时不显示
          },
        },
      };
    });

    // 配置 ECharts 图表选项
    const option = {
      title: {
        text: '入职时间与薪资关系柱状图',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: {
        data: majors,
        bottom: 0,
      },
      xAxis: {
        type: 'category',
        data: years.map((year) => `${year}年`), // 格式化横坐标显示
        name: '入职年限',
      },
      yAxis: {
        type: 'value',
        name: '薪资',
      },
      series,
    };

    // 渲染图表
    chart.setOption(option);
  }
};


// 刷新图表逻辑
const refreshChart = async () => {
  const response = await getMajorStatisticsApi({ year: year.value });
  if (response.code === 200) {
    const data = response.data;

    // 判断数据状态
    hasData1.value = data.majorAvgSalaryList.length > 0;
    hasData2.value = data.employmentRateList.length > 0;
    hasData3.value = data.majorSalaryList.length > 0;
    hasData4.value = data.avgSalaryList.length > 0;

    // 根据选定图表类型刷新图表
    if (selectedChart.value === 'avgSalaryPieChart' && hasData1.value)
      await createAvgSalaryPieChart(data.majorAvgSalaryList);
    else if (selectedChart.value === 'employmentRatePieChart' && hasData2.value)
      await createEmploymentRatePieChart(data.employmentRateList
      );
    else if (selectedChart.value === 'majorSalaryBarChart' && hasData3.value)
      await createMajorSalaryBarChart(data);
    else if (selectedChart.value === 'avgSalaryChart' && hasData4.value)
      await createAvgSalaryBarChart(data);
  } else {
    ElMessage.error('获取方向数据失败或暂无数据');
  }
};

// 切换图表
const onChartSelect = async () => {
  // 切换图表时先销毁当前图表实例
  await destroyCharts();
  // 根据选中图表调用刷新函数
  await refreshChart();
};

// 销毁所有图表实例
const destroyCharts = async () => {
  if (avgSalaryPieChartRef.value) echarts.dispose(avgSalaryPieChartRef.value);
  if (employmentRatePieChartRef.value)
    echarts.dispose(employmentRatePieChartRef.value);
  if (majorSalaryBarChartRef.value)
    echarts.dispose(majorSalaryBarChartRef.value);
  if (avgSalaryChartRef.value) echarts.dispose(avgSalaryChartRef.value);
};


// 数据加载和处理逻辑
const searchYear = async () => {
  const response = await getMajorStatisticsApi({ year: year.value });
  console.log('数据获取成功', response);
  if (response.code === 200) {
    if (response.data.majorAvgSalaryList.length > 0) {
      hasData1.value = true;
    } else {
      hasData1.value = false;
    }
    if (response.data.employmentRateList.length > 0) {
      hasData2.value = true;
    } else {
      hasData2.value = false;
    }
    if (response.data.majorSalaryList.length > 0) {
      hasData3.value = true;
    } else {
      hasData3.value = false;
    }
    if (response.data.avgSalaryList
      .length > 0) {
      hasData4.value = true;
    } else {
      hasData4.value = false;
    }
    createAvgSalaryPieChart(response.data.majorAvgSalaryList
    );
    createEmploymentRatePieChart(response.data.employmentRateList);
    createMajorSalaryBarChart(response.data);
    createAvgSalaryBarChart(response.data);
  } else {
    ElMessage.error('获取方向数据失败');
  }
};

// 挂载时初始化图表
onMounted(() => {
  searchYear();
});
</script>